﻿using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;

namespace zaklad_rtv
{
    /// <summary>
    /// Interaction logic for ServiceForm.xaml
    /// </summary>
    public partial class ServiceForm
    {
        private Collection<Client> _clientCollection;

        public Collection<Client> ClientCollection
        {
            get { return _clientCollection; }
            set
            {
                _clientCollection = value;
                _comboBoxClient.ItemsSource = _clientCollection;
                RefreshComboBox();
            }
        }

        public ServiceForm()
        {
            InitializeComponent();
        }

        protected override void FillFormFromObject()
        {
            MainWindow._serviceFormTab.Header = "Edytuj naprawę";
            var service = (Service)EditObject;
            _tbNumber.Text = service.Number.ToString(CultureInfo.InvariantCulture);
            _comboBoxClient.SelectedItem = service.Client;
            _tbBeginServiceDate.Text = service.BeginServiceDate.ToString(StringConstants.DateFormat);
            _tbCost.Text = CostConverter.NumberToText(service.Cost);
            _tbDefectDescription.Text = service.DefectDescription;
            _tbEndServiceDate.Text = service.EndServiceDate.Equals(DateTime.MaxValue) ? "" : service.EndServiceDate.ToString(StringConstants.DateFormat);
            _tbHardwareType.Text = service.HardwareType;
            _tbRemarks.Text = service.Remarks;
            _tbServiceDescription.Text = service.ServiceDescription;
        }

        protected override void ResetForm()
        {
            MainWindow._serviceFormTab.Header = "Nowa naprawa";
            _tbNumber.Text = "[generowany automatycznie]";
            _comboBoxClient.SelectedItem = null;
            _tbBeginServiceDate.Text = DateTime.Now.ToString(StringConstants.DateFormat);
            _tbCost.Text = "";
            _tbDefectDescription.Text = "";
            _tbEndServiceDate.Text = "";
            _tbHardwareType.Text = "";
            _tbRemarks.Text = "";
            _tbServiceDescription.Text = "";
        }

        private void ClearForm(object sender, RoutedEventArgs e)
        {
            EditObject = null;
        }

        private void SaveForm(object sender, RoutedEventArgs e)
        {
            if (ValidateForm())
            {
                var service = new Service
                {
                    BeginServiceDate = DateTime.Parse(_tbBeginServiceDate.Text),
                    Client = _comboBoxClient.SelectedItem as Client,
                    ClientId = ((Client)_comboBoxClient.SelectedItem).Id,
                    Cost = CostConverter.TextToNumber(_tbCost.Text),
                    DefectDescription = _tbDefectDescription.Text,
                    EndServiceDate = string.IsNullOrEmpty(_tbEndServiceDate.Text.Trim()) ? DateTime.MaxValue : DateTime.Parse(_tbEndServiceDate.Text),
                    HardwareType = _tbHardwareType.Text,
                    Remarks = _tbRemarks.Text,
                    ServiceDescription = _tbServiceDescription.Text
                };
                if (EditObject != null && EditObject.Id > 0)
                {
                    service.Id = EditObject.Id;
                    service.Number = ((Service)EditObject).Number;
                    MainWindow.DBHelper.Update(service);
                    RaiseEvent(new DatabaseObjectChangedEventArgs(AppEvents.DatabaseObjectChangedEvent, sender, service, EventAction.Update));
                    MessageBox.Show("Pomyślnie edytowano naprawę!", "Sukces", MessageBoxButton.OK,
                                    MessageBoxImage.Information);
                    EditObject = null;
                }
                else
                {
                    service.Number = MainWindow.DBHelper.GenerateServiceNumber();
                    MainWindow.DBHelper.Save(service);
                    RaiseEvent(new DatabaseObjectChangedEventArgs(AppEvents.DatabaseObjectChangedEvent, sender, service, EventAction.Insert));
                    MessageBox.Show("Pomyślnie dodano naprawę!", "Sukces", MessageBoxButton.OK,
                                    MessageBoxImage.Information);
                    EditObject = null;
                }
                MainWindow.ChangeActiveTab(MainWindow.Tabs.ServiceList);
            }
        }

        protected override bool ValidateForm()
        {
            var errors = new StringBuilder();
            var validationResult = true;
            if (_comboBoxClient.SelectedItem == null)
            {
                errors.AppendLine("Należy wybrać klienta.");
                validationResult = false;
            }
            if (string.IsNullOrEmpty(_tbHardwareType.Text.Trim()))
            {
                errors.AppendLine("Należy podać typ sprzętu.");
                validationResult = false;
            }
            if (string.IsNullOrEmpty(_tbBeginServiceDate.Text.Trim()))
            {
                errors.AppendLine("Należy podać datę przyjęcia sprzętu.");
                validationResult = false;
            }
            else if (!IsDateCorrect(_tbBeginServiceDate))
            {
                errors.AppendLine("Data przyjęcia ma niewłaściwy format.");
                validationResult = false;
            }
            if (!string.IsNullOrEmpty(_tbEndServiceDate.Text.Trim()) && !IsDateCorrect(_tbEndServiceDate))
            {
                errors.AppendLine("Data odbioru ma niewłaściwy format.");
                validationResult = false;
            }
            if (!string.IsNullOrEmpty(_tbCost.Text.Trim()) && !IsCostCorrect(_tbCost))
            {
                errors.AppendLine("Koszt naprawy ma niewłaściwy format.");
                validationResult = false;
            }
            var errorString = errors.ToString();
            if (!string.IsNullOrEmpty(errorString))
            {
                MessageBox.Show(errorString, "Błąd", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            return validationResult;
        }

        private void GoToNewClient(object sender, RoutedEventArgs e)
        {
            MainWindow._clientFormTab.Header = "Nowy klient";
            ((ClientForm)MainWindow._clientFormTab.Content).EditObject = null;
            MainWindow.ChangeActiveTab(MainWindow.Tabs.ClientForm);
        }

        public void ClientAdded(Client client)
        {
            ClientCollection.Add(client);
            RefreshComboBox();
        }

        public void ClientEdited(Client client)
        {
            RefreshComboBox();
        }

        public void ClientDeleted(Client client)
        {
            ClientCollection.Remove(client);
            RefreshComboBox();
        }

        private void RefreshComboBox()
        {
            _comboBoxClient.ItemsSource = null;
            _comboBoxClient.ItemsSource =
                from c in ClientCollection
                orderby c.LastName, c.FirstName
                select c;
        }

        private bool IsCostCorrect(TextBox tb)
        {
            var text = tb.Text;
            var pattern = new Regex("^[0-9]+(,[0-9]{1,2})?$");
            return pattern.IsMatch(text);

        }

        private bool IsDateCorrect(TextBox tb)
        {
            var text = tb.Text;
            var pattern = new Regex("^[0-9]{4}-[0-9]{2}-[0-9]{2}$");
            return pattern.IsMatch(text);
        }
    }
}
